import 'package:flutter/material.dart';
import '../base_function.dart';
import 'package:flutter_base_plugin/flutter_base_plugin.dart';

///@description:View 基类,配合[BaseViewModel]使用
///封装http通用加载错误页，空白页以及正常显示页UI和逻辑，UI可自定义
abstract class BaseProviderState<VM extends BaseViewModel,
        T extends StatefulWidget> extends State<T>
    with BaseFunction, AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => false;

  @override
  void initState() {
    initBaseCommon(this, context);
    buildCreate();
    super.initState();
  }

  @override
  // ignore: must_call_super
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,

      ///实现点击空白区域隐藏键盘
      body: GestureDetector(
        onTap: () {
          hideKeyboard();
        },
        child: getBaseView(context),
      ),
    );
  }

  ///返回UI控件 相当于setContentView()
  Widget buildWidget(VM viewModel, BuildContext context);

  Widget getBaseView(BuildContext context) {
    return Column(
      children: <Widget>[
        _getAppBar(),
        Container(
          width: getScreenWidth(),
          height: getMainWidgetHeight(),
          color: backgroundColor, //背景颜色，可自己变更
          child: // TODO: implement build
              ChangeNotifierProvider<VM>.value(
            value: buildViewModel(),
            child: Consumer<VM>(
              builder: (BuildContext context, VM vm, Widget? child) {
                if (vm.isSuccess()) {
                  return buildWidget(vm, context);
                } else {
                  return FutureBuilder(
                    future: vm.onLoading(),
                    builder: (context, snapshot) {
                      if (snapshot.connectionState == ConnectionState.done) {
                        if (vm.isFail()) {
                          ///加载失败
                          return _getErrorWidget(vm);
                        } else if (vm.isEmpty()) {
                          ///数据为空
                          return _getEmptyWidget(vm);
                        } else {
                          ///加载成功
                          return buildWidget(vm, context);
                        }
                      } else {
                        ///加载中
                        return isShowLoadWidget
                            ? _getLoadingWidget()
                            : const Text("");
                      }
                    },
                  );
                }
              },
            ),
          ),
        ),
      ],
    );
  }

  Widget _getAppBar() {
    return buildBaseAppBar() ??
        Column(
          children: [
            getBaseTopBar(),
            getBaseAppBar(),
          ],
        );
  }

  Widget _getErrorWidget(VM viewModel) {
    return buildErrorWidget(viewModel.error) ??
        LoadStateParentView(
          (BasePlugin.loadConfig.configLoadErrorView() ?? LoadErrorView()),
          _onRefresh(viewModel),
        );
  }

  Widget? buildErrorWidget(HttpErrorBean? error) {
    return null;
  }

  Widget? buildBaseAppBar() {
    return null;
  }

  Widget? buildEmptyWidget() {
    return null;
  }

  Widget _getEmptyWidget(VM viewModel) {
    return buildEmptyWidget() ??
        LoadStateParentView(
          (BasePlugin.loadConfig.configLoadEmptyView() ?? LoadEmptyView()),
          _onRefresh(viewModel),
        );
  }

  Widget _getLoadingWidget() {
    return LoadStateParentView(
      (BasePlugin.loadConfig.configLoadingView() ?? LoadingView()),
      null,
    );
  }

  ///刷新页面
  VoidCallback _onRefresh(VM viewModel) {
    return () {
      viewModel.notifyListeners();
    };
  }

  //TODO:隐藏键盘
  void hideKeyboard() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  VM buildViewModel();

  @override
  void buildCreate();

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }
}
